package com.example.web.controller;

import com.example.web.entity.AnalysisData;
import com.example.web.entity.Result;
import com.example.web.service.AnalysisService;
import com.example.web.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 智能分析控制器
 */
@RestController
@RequestMapping("/api/analysis")
@CrossOrigin(origins = "http://localhost:3001", allowCredentials = "true")
public class AnalysisController {
    
    @Autowired
    private AnalysisService analysisService;
    
    @Autowired
    private JwtUtils jwtUtils;
    
    /**
     * 获取预警信息
     */
    @GetMapping("/alerts")
    public Result<List<AnalysisData.AlertInfo>> getAlerts(HttpServletRequest request) {
        try {
            Long creatorId = getCurrentUserId(request);
            if (creatorId == null) {
                return Result.error(401, "未认证");
            }
            
            List<AnalysisData.AlertInfo> alerts = analysisService.getAlertInfo(creatorId);
            return Result.success(alerts);
        } catch (Exception e) {
            return Result.error("获取预警信息失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取近30日新增客户趋势数据
     */
    @GetMapping("/customer-trend")
    public Result<List<AnalysisData.CustomerTrendData>> getCustomerTrend(HttpServletRequest request) {
        try {
            Long creatorId = getCurrentUserId(request);
            if (creatorId == null) {
                return Result.error(401, "未认证");
            }
            
            List<AnalysisData.CustomerTrendData> trendData = analysisService.getCustomerTrendData(creatorId);
            return Result.success(trendData);
        } catch (Exception e) {
            return Result.error("获取客户趋势数据失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取高价值客户列表
     */
    @GetMapping("/high-value-customers")
    public Result<Map<String, Object>> getHighValueCustomers(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String keyword,
            HttpServletRequest request) {
        try {
            Long creatorId = getCurrentUserId(request);
            if (creatorId == null) {
                return Result.error(401, "未认证");
            }
            
            Map<String, Object> result = analysisService.getHighValueCustomers(creatorId, page, size, keyword);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("获取高价值客户列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 导出高价值客户数据
     */
    @GetMapping("/high-value-customers/export")
    public Result<List<AnalysisData.HighValueCustomer>> exportHighValueCustomers(
            @RequestParam(required = false) String keyword,
            HttpServletRequest request) {
        try {
            Long creatorId = getCurrentUserId(request);
            if (creatorId == null) {
                return Result.error(401, "未认证");
            }
            
            List<AnalysisData.HighValueCustomer> customers = analysisService.exportHighValueCustomers(creatorId, keyword);
            return Result.success(customers);
        } catch (Exception e) {
            return Result.error("导出高价值客户数据失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取当前登录用户ID
     */
    private Long getCurrentUserId(HttpServletRequest request) {
        try {
            String token = extractTokenFromRequest(request);
            if (token == null) {
                return null;
            }
            
            String username = jwtUtils.getUsernameFromToken(token);
            if (jwtUtils.validateToken(token, username)) {
                return jwtUtils.getUserIdFromToken(token);
            }
            return null;
        } catch (Exception e) {
            return null;
        }
    }
    
    /**
     * 从请求中提取Token
     */
    private String extractTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}